#ifndef _SOCKET_H_XWW_20050123__
#define _SOCKET_H_XWW_20050123__
//Socket.h

#ifdef __cplusplus
extern "C" {
#endif


#ifdef _MSC_VER
	#include <winsock2.h>
	#define socket_errno WSAGetLastError()
	typedef unsigned long in_addr_t;
	typedef int socklen_t;
	#define SHUT_WR SD_SEND
	#define SHUT_RD SD_RECEIVE
	#define SHUT_RDWR SD_BOTH

#elif __GNUC__

	#include <sys/ioctl.h>
	#include <sys/types.h>
	#include <sys/socket.h>
	#include <netinet/in.h>
	#include <arpa/inet.h>
	#include <errno.h>
	#include <unistd.h>
	#include <fcntl.h>
	#include <netdb.h>

	#ifndef ADDR_ANY
		#define ADDR_ANY                INADDR_ANY
	#endif


	#ifndef SOCKET
		#define SOCKET int
		#define INVALID_SOCKET -1
		#define SOCKET_ERROR -1
	#endif

	#ifndef NO_ERROR
		#define NO_ERROR 0
	#endif
	#ifndef closesocket
		#define closesocket close
	#endif
	#ifndef ioctlsocket
		#define ioctlsocket ioctl
	#endif
	#ifndef socket_errno
		#define socket_errno errno
	#endif
	
	#define SD_SEND SHUT_WR 
	#define SD_RECEIVE SHUT_RD 
	#define SD_BOTH SHUT_RDWR 
#else
	#error nonsupport
#endif

typedef struct sockaddr_in sockaddr_in;
typedef struct sockaddr sockaddr;
typedef struct in_addr in_addr;

/**like inet_addr
 *@cp: "www.sina.com.cn" or "200.200.0.1"
 *@return: net order ip
 */
in_addr_t inet_addr_ex(const char* cp);

int Socket_SetNonblock(SOCKET fd, long act) ;
int Socket_SetNoDelay(SOCKET fd, long act) ;
int Socket_SetLinger(SOCKET fd, u_short l_onoff, u_short l_linger);
int Socket_SetKeepAlive(SOCKET fd, long act) ;

/**
 * recv within timeout
 * @param fd : socket
 * @param buffer : data
 * @param size : data size
 * @param sec : second
 * @return -1 : socket error
 *		    0 : recv close
 *			-2 : timeout
 *			size: success
 */
int Socket_RecvTimeout(SOCKET fd, void* buffer, int size, int sec);

/**
 * recv once
 *@return -1 : socket error
 *        0 : recv close
 *	 	 -2 : timeout
 *		  >0: success
 */
int Socket_RecvOnceTimeout(SOCKET fd, void* buffer, int size, int sec);

#ifdef __cplusplus
}
#endif 
#endif //_SOCKET_H_XWW_20050123__
